package com.booleansoft.redirect;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.List;

import com.booleansoft.redirect.cmmd.BaseCommand;
import com.booleansoft.util.XTCoding;

public class ThreadServerRunable implements Runnable{

	private Socket socket;
	public ThreadServerRunable(Socket socket) {
		super();
		this.socket = socket;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	public void run() {
		// TODO Auto-generated method stub
		try {
			DataInputStream in=new DataInputStream(socket.getInputStream());
			DataOutputStream out=new DataOutputStream(socket.getOutputStream());
			String cmd=in.readUTF();
			if(cmd.startsWith("login ")){
				String[] params=cmd.split("\\s+");
				String user=params[1];
				String code=params[2];
				boolean flag=XTCoding.check(code);
				if(!flag){
					return;
				}
				out.writeUTF("ok");
				Thread.currentThread().setName("user-login:"+user);
				while((cmd=in.readUTF())!=null){
					if(cmd.endsWith("exit")){
						String bak="ok";
						out.writeUTF(bak);
						socket.close();
						break;
					}
					List<BaseCommand> list=BaseCommand.getCMDList();
					boolean hasCMD=false;
					for(BaseCommand c:list){
						if(c.exec(cmd.trim(), socket, in, out)){
							hasCMD=true;
							break;
						}
					}
					if(!hasCMD){
						StringBuffer hsb=new StringBuffer();
						for(BaseCommand c:list){
							hsb.append(c.getHelp()).append("\r\n");
						}
						out.writeUTF(hsb.toString());
					}
					
				}
				
			}
		} catch (Exception e) {
		}finally{
			if(socket!=null){
				try {
					socket.close();
				} catch (IOException e) {}
			}
		}
	}

}
